import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface BlogArticle {
  id: number
  title: string
  slug: string
  excerpt: string
  content: string
  image: string
  category: string
  tags: string[]
  date: string
  readingTime: number
}

export const useBlogStore = defineStore('blog', () => {
  // 文章数据
  const articles = ref<BlogArticle[]>([
    {
      id: 1,
      title: '使用Vue 3和TypeScript构建现代Web应用',
      slug: 'building-modern-web-apps-with-vue3-typescript',
      excerpt: '探索Vue 3的新特性和TypeScript的类型安全如何提升开发体验和代码质量...',
      content: `
        <h2>Vue 3的新特性</h2>
        <p>Vue 3引入了许多令人兴奋的新特性，包括：</p>
        <ul>
          <li>Composition API - 更灵活的逻辑复用方式</li>
          <li>更好的TypeScript支持</li>
          <li>性能提升 - 更快的渲染速度和更小的包大小</li>
          <li>Teleport组件 - 轻松实现模态框等需要DOM外渲染的组件</li>
        </ul>

        <h2>TypeScript的优势</h2>
        <p>TypeScript为Vue开发带来了诸多好处：</p>
        <ol>
          <li>类型安全 - 减少运行时错误</li>
          <li>更好的IDE支持 - 自动补全和类型检查</li>
          <li>更易维护的代码 - 明确的接口定义</li>
        </ol>

        <h2>最佳实践</h2>
        <p>结合Vue 3和TypeScript的一些最佳实践：</p>
        <pre><code>// 使用defineComponent定义组件
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MyComponent',
  props: {
    message: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // 类型安全的props访问
    const reversedMessage = computed(() => props.message.split('').reverse().join(''))

    return { reversedMessage }
  }
})</code></pre>
      `,
      image:
        'https://img0.baidu.com/it/u=798641325,1866839818&fm=253&fmt=auto&app=120&f=JPEG?w=749&h=500',
      category: 'Programming',
      tags: ['Vue 3', 'TypeScript', 'Frontend'],
      date: '2024-01-15',
      readingTime: 5,
    },
    {
      id: 2,
      title: '响应式设计最佳实践',
      slug: 'responsive-design-best-practices',
      excerpt: '学习创建真正响应式的网站设计，适应各种设备尺寸和用户需求...',
      content: `
        <h2>响应式设计基础</h2>
        <p>响应式设计的核心原则：</p>
        <ul>
          <li>流动布局 - 使用百分比而非固定宽度</li>
          <li>媒体查询 - 针对不同屏幕尺寸应用不同样式</li>
          <li>弹性图片 - 图片能自动调整大小</li>
        </ul>

        <h2>现代CSS技术</h2>
        <p>提升响应式设计的现代CSS技术：</p>
        <ul>
          <li>CSS Grid - 强大的二维布局系统</li>
          <li>Flexbox - 一维布局的理想选择</li>
          <li>CSS变量 - 动态调整样式</li>
        </ul>

        <h2>移动优先策略</h2>
        <p>为什么移动优先设计很重要：</p>
        <ol>
          <li>移动设备用户占比高</li>
          <li>强制简化设计</li>
          <li>渐进增强而非优雅降级</li>
        </ol>
      `,
      image:
        'https://img0.baidu.com/it/u=275044674,3775024324&fm=253&fmt=auto&app=120&f=JPEG?w=809&h=500',
      category: 'Design',
      tags: ['CSS', 'Responsive Design', 'UI/UX'],
      date: '2024-01-10',
      readingTime: 4,
    },
    // 添加更多示例文章...
  ])

  // 加载状态
  const isLoading = ref(false)

  // 分页相关状态
  const currentPage = ref(1)
  const pageSize = ref(6)
  const total = computed(() => articles.value.length)

  // 分类列表
  const categories = computed(() => {
    const categorySet = new Set(articles.value.map((article) => article.category))
    return Array.from(categorySet)
  })

  // 标签列表
  const tags = computed(() => {
    const tagSet = new Set(articles.value.flatMap((article) => article.tags))
    return Array.from(tagSet)
  })

  // 获取分页文章
  const getPaginatedArticles = (page: number, size: number) => {
    const start = (page - 1) * size
    const end = start + size
    return articles.value.slice(start, end)
  }

  // 根据条件筛选文章
  const filterArticles = (params: {
    search?: string
    category?: string
    tag?: string
    page: number
    pageSize: number
  }) => {
    isLoading.value = true

    try {
      let filtered = [...articles.value]

      // 搜索过滤
      if (params.search) {
        const searchLower = params.search.toLowerCase()
        filtered = filtered.filter(
          (article) =>
            article.title.toLowerCase().includes(searchLower) ||
            article.excerpt.toLowerCase().includes(searchLower),
        )
      }

      // 分类过滤
      if (params.category) {
        filtered = filtered.filter((article) => article.category === params.category)
      }

      // 标签过滤
      if (params.tag) {
        filtered = filtered.filter((article) => article.tags.includes(params.tag || ''))
      }

      // 计算总数
      const totalFiltered = filtered.length

      // 分页
      const start = (params.page - 1) * params.pageSize
      const end = start + params.pageSize
      const paginatedResults = filtered.slice(start, end)

      return {
        articles: paginatedResults,
        total: totalFiltered,
      }
    } finally {
      isLoading.value = false
    }
  }

  // 获取单篇文章
  const getArticleBySlug = (slug: string) => {
    return articles.value.find((article) => article.slug === slug)
  }

  // 获取相关文章
  const getRelatedArticles = (currentSlug: string, limit = 3) => {
    const currentArticle = getArticleBySlug(currentSlug)
    if (!currentArticle) return []

    return articles.value
      .filter(
        (article) =>
          article.slug !== currentSlug &&
          (article.category === currentArticle.category ||
            article.tags.some((tag) => currentArticle.tags.includes(tag))),
      )
      .slice(0, limit)
  }

  // 模拟API调用加载文章
  const loadArticles = async () => {
    isLoading.value = true
    try {
      // 这里可以添加实际的API调用
      // 现在使用setTimeout模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000))
      // 实际项目中这里会从API获取文章数据
      // articles.value = await api.getArticles()
    } finally {
      isLoading.value = false
    }
  }
  
  if (import.meta.hot) {
    import.meta.hot.accept(acceptHMRUpdate(useBlogStore, import.meta.hot))
  }

  return {
    articles,
    isLoading,
    currentPage,
    pageSize,
    total,
    categories,
    tags,
    getPaginatedArticles,
    filterArticles,
    getArticleBySlug,
    getRelatedArticles,
    loadArticles,
  }
})
